var formulaWarning = new sap.ui.commons.Image({src: "resources/images/btnWarning.png", width:"20px", heigh:"20px", visible : false});

function showFormula_JSEvent(oParameter)
{
	showFormula(arguments[0].srcElement);
}

function showFormula(source)
{
	var oDialog = null;
	var tbxFormula = null;
	var tbxNewParameter = null;
	var removedParameter = null;
	var paramToComponents = {};
	var valID = source.id.replace("formula","");
	var lastComponents = {"tbxFormula": {}, "tbFormula": {}, "tbxParameter" : {}, "btnAdd" : {}};
	var lbFormulaError = new sap.ui.commons.Label({visible : false});
	var k = 0;
	var firstLetter = "A";
	var paramsToLetters = [];
	
	function newWarning()
	{
		return new sap.ui.commons.Image({src: "resources/images/btnWarning.png", width:"20px", heigh:"20px", visible: false});
	}
	
	function getParamsLetters()
	{
		var params = [];
		for(var i = 0 ; i < paramsToLetters.length ; i++)
			if(paramsToLetters[i] != null)
				params.push(paramsToLetters[i].paramLetter);
		
		return params;
	}
	
	function replaceAll(currentStr, oldStr, newStr) 
	{
		var retVal = currentStr;
		
		while(retVal.indexOf(oldStr) != -1)
			retVal = retVal.replace(oldStr, newStr);
		
		return retVal;
	}
	
	function showSyntaxError(oControlEvent)
	{
		var validateFormulaReq = getXmlHttpRequestObject();
		lbFormulaError.setVisible(false);
		//Show a label in red with the error message...
		var formula = tbxFormula.getValue();
		if(formula == null || formula.trim() == "")
		{
			lbFormulaError.setText("Formula cannot be empty.");
			lbFormulaError.setVisible(true);
		}
		
		for(var i = 0 ; i < paramsToLetters.length ; i++)
		{
			var visible = false;
			if(formula.indexOf(paramsToLetters[i].paramLetter) == -1)
				visible = true;
				
			paramToComponents[paramsToLetters[i].paramID]["warning"].setVisible(visible);
		}
		
		function handleRequest()
		{
			if(validateFormulaReq.readyState == 4 && validateFormulaReq.status == 200) 
		    {
				eval("var response = ("+validateFormulaReq.responseText+")");
				
		     	if(response == "MISSING_PARAMETER")
		     	{
		     		formulaWarning.setVisible(true);
					lbFormulaError.setText("Warning: There are parameters not yet defined in the formula.");
					lbFormulaError.setVisible(true);
		     	}
		     	else
		     		formulaWarning.setVisible(false);
		    }
		}
		
		var paramFor = "&formula=" + encodeURIComponent(formula);
		paramFor += "&parameters=" + transformJSON(getParamsLetters());
		sendRequest(validateFormulaReq, "method", "validateFormula", handleRequest, paramFor);
	}
	
	function saveFormula(oControlEvent)
	{
		var control = oControlEvent;
		var formula = tbxFormula.getValue();
		if(formula != null && formula.trim() != "")
		{
			lbFormulaError.setVisible(false);
			var validateFormulaReq = getXmlHttpRequestObject();
			
			function handleRequest()
			{
				function requestSave()
				{
					var saveReq = getXmlHttpRequestObject();
					var hasSaveError = true;
					
					function handleSaveRequest()
					{
						if(saveReq.readyState == 4 && saveReq.status == 200) 
					    {
					     	eval("var response = ("+saveReq.responseText+")");
					     	if(typeof response != "string")
					     	{
					     		refreshResultFields(response);
			     				closeDialog(control);
			     				hasSaveError = false;
					     	}
					     	if(response == "CALCULATION_METHOD_NOT_FOUND")
					     	{
					     	}
					     	else 
					     		showSpecifcErrorMessage(response);
					    }
					}
					
					var parameters = [];
					for(var i = 0 ; i < paramsToLetters.length ; i++)
					{
						var paramID = paramsToLetters[i].paramID;
						var param = {"name": paramToComponents[paramID].tbxParam.getValue(), "paramID": paramID, "letter": paramsToLetters[i].paramLetter};
						parameters.push(param);
					}
					
					var paramFor = "&formula=" + encodeURIComponent(formula);
					paramFor += "&parameters=" + transformJSON(parameters);
					paramFor += "&valID=" + transformJSON(valID);
					
					sendRequest(saveReq, "method", "saveFormula", handleSaveRequest, paramFor);
					return hasSaveError;
				}
				
				if(validateFormulaReq.readyState == 4 && validateFormulaReq.status == 200) 
			    {
			     	eval("var response = ("+validateFormulaReq.responseText+")");
			     	
			     	if(response == "MISSING_PARAMETER")
			     	{
			     		function callback(oAction)
			     		{
			     			var valueID = source.id.replace("formula","");
			     			var currentLine = findParentByTagName(source, "TD");
			     			
			     			if(oAction == sap.ui.commons.MessageBox.Action.YES)
			     			{
			     				if(requestSave())
			     				{
			     					if(getChildElementByProperty(currentLine, "id", "warning" + valueID) == null)
				     					currentLine.appendChild(createImageButton("warning" + valueID, imgWarning, showFormula_JSEvent, "smallImgButton"));
				     				getChildElementByProperty(currentLine, "id", "result" + valueID).innerHTML = "ERROR";
			     				}
			     			}
			     		}
			     		
			     		sap.ui.commons.MessageBox.show("The formula uses parameters that are not defined yet. Are you sure you want to save the formula?", sap.ui.commons.MessageBox.Icon.QUESTION, "Confirm Save", [sap.ui.commons.MessageBox.Action.YES, sap.ui.commons.MessageBox.Action.NO], callback);
			     	}
			     	else if(response == "INVALID_SYNTAX")
			     	{
			     		lbFormulaError.setText("The formula has an incorrect syntax. Please check the formula and correct the erros.");
			     		lbFormulaError.setVisible(true);
			     	}
			     	else
			     		requestSave();
			    }
			}
			
			var paramFor = "&formula=" + encodeURIComponent(formula);
			paramFor += "&parameters=" + transformJSON(getParamsLetters());
			sendRequest(validateFormulaReq, "method", "validateFormula", handleRequest, paramFor);
		}
	}
	
	function getParameterByLetter(paramsLetter)
	{
		var paramID = null;
		
		for(var i = 0 ; i < paramsToLetters.length ; i++)
			if(paramsLetter == paramsToLetters[i].paramLetter)
			{
				paramID = paramsToLetters[i].paramID;
				break;
			}
		
		return paramID;
	}
	
	function getLetterByParameter(paramID)
	{
		for(var i = 0 ; i < paramsToLetters.length ; i++)
			if(paramID == paramsToLetters[i].paramID)
				return paramsToLetters[i].paramLetter;
	}
	
	function addParameter(oControlEvent)
	{
		var paramID = new Date().getTime();
		var paramLetter = null;
		
		if(removedParameter != null)
		{
			paramLetter = removedParameter.letter;
			paramsToLetters[removedParameter.index] = {"paramID": paramID, "paramLetter": paramLetter};
			removedParameter = null;
		}
		else
		{
			paramLetter = String.fromCharCode(firstLetter.charCodeAt(0) + k++);
			paramsToLetters.push({"paramID": paramID, "paramLetter": paramLetter});
		}
			
		var warning = newWarning();
		var lbParam = new sap.ui.commons.Label({text : paramLetter});
		var tbxParam = new sap.ui.commons.TextField(new Date().getTime());
		tbxParam.setValue(tbxNewParameter.getValue());
		var oBtnRemove = new sap.ui.commons.Button({text: "Remove", press:removeParameter});
		
		oDialog.addContent(warning);
		oDialog.addContent(lbParam);
		oDialog.addContent(tbxParam);
		oDialog.addContent(oBtnRemove);
		oDialog.addContent(oBtnRemove);
	
		tbxNewParameter.setValue(String.fromCharCode(firstLetter.charCodeAt(0) + k) + ' - ');
		
		var components = {"btnRemove": oBtnRemove, "label": lbParam, "tbxParam": tbxParam, "warning": warning};
		paramToComponents[paramID] = components;
		
		refreshLastComponents();
	}
	
	function removeParameter(oControlEvent)
	{
		var btnSource = oControlEvent.getSource();
		components = getComponentsByComponent(btnSource, "btnRemove");
		
		for(var key in components)
			oDialog.removeContent(components[key]);
		
		for(var i = 0 ; i < paramsToLetters.length ; i++)
			if(paramToComponents[paramsToLetters[i].paramID] == components)
			{
				removedParameter = {"index": i, "letter": paramsToLetters[i].paramLetter};
				tbxNewParameter.setValue(paramsToLetters[i].paramLetter + " - ");
				paramsToLetters[i] = null;
				components = null;
				break;
			}
		
		//verificar se a formula contem o elemento removido se continver, exibir warning...se nao tiver nao exiber anda
	}
	
	function getComponentsByComponent(component, property)
	{
		var components = {};
		for(var i = 0 ; i < paramsToLetters.length ; i++)
			if(paramToComponents[paramsToLetters[i].paramID][property] == component)
			{
				components = paramToComponents[paramsToLetters[i].paramID];
				break;
			}
		
		return components;
	}
	
	function obtainFormula(valID)
	{
		var formula = null;
		var formulaReq = getXmlHttpRequestObject();
		
		function handleRequest()  
		{  
			if (formulaReq.readyState == 4 && formulaReq.status == 200) 
		    {
		     	eval("var response = ("+formulaReq.responseText+")");
		     	
		     	if(typeof response != "string")
		     		formula = response;
		     	else
		     		showSpecifcErrorMessage(response);
		    }
		}
		
		var param = "&valID=" + transformJSON(valID);
		sendRequest(formulaReq, "method", "getFormula", handleRequest, param);
		
		return formula;
	}
	
	var mainCrtID = findParentByTagName(source, "TABLE").id;
	var mainCrtName = document.getElementById("name" + mainCrtID).value;
	var calMet = obtainFormula(valID);
	var formula = (calMet.formula != null) ? calMet.formula : {"formula": "", "parameters": calMet.parameters};
	var expression = formula.formula;
	var oBtnOpen = new sap.ui.commons.Button({text: "Save", press:saveFormula});
	
	oDialog = createDialog("Edit Formula", oBtnOpen);
	oDialog.addContent(new sap.ui.commons.Label({text : '   The ' + mainCrtName + ' is caclulated'}));
	oDialog.addContent(new sap.ui.commons.Label({text : ' based on the following parameters: '}));
	
	var metParameters = formula.parameters;
	for(k = 0 ; k < metParameters.length ; k++)
	{
		var paramLetter = String.fromCharCode(firstLetter.charCodeAt(0) + k);  
		var paramID = metParameters[k].ID;
		var paramName = metParameters[k].name;

		var warning = newWarning();
		var lbParam = new sap.ui.commons.Label({text : paramLetter});
		var tbxParam = new sap.ui.commons.TextField(new Date().getTime());
		tbxParam.setValue(paramName);
		var oBtnRemove = new sap.ui.commons.Button({text: "Remove", press:removeParameter});
		
		oDialog.addContent(warning);
		oDialog.addContent(lbParam);
		oDialog.addContent(tbxParam);
		oDialog.addContent(oBtnRemove);
		
		lastParamIndex = oDialog.indexOfContent(lbParam) +1;
		
		expression = replaceAll(expression, paramID, paramLetter);
		var paramToLetter = {"paramID": paramID, "paramLetter": paramLetter};
		paramsToLetters.push(paramToLetter);
		
		var components = {"btnRemove": oBtnRemove, "label": lbParam, "tbxParam": tbxParam, "warning": warning};
		paramToComponents[paramID] = components;
	}
	
	function refreshLastComponents()
	{
		for(var key in lastComponents)
			oDialog.removeContent(lastComponents[key]);
		
		for(var key in lastComponents)
			oDialog.addContent(lastComponents[key]);
	}
	
	var oBtnAdd = new sap.ui.commons.Button({text: "Add", press:addParameter});
	oBtnAdd.setWidth("30px");
	
	tbxNewParameter = new sap.ui.commons.TextField(new Date().getTime());
	tbxNewParameter.setWidth("205px");
	var paramLetter = String.fromCharCode(firstLetter.charCodeAt(0) + k);
	tbxNewParameter.setValue(paramLetter + ' - ');
	
	var lbFormula = new sap.ui.commons.Label({text : 'Formula: '});    
	tbxFormula = new sap.ui.commons.TextField(new Date().getTime());
	tbxFormula.setWidth("250px");
	tbxFormula.setValue(expression);
	tbxFormula.attachChange(showSyntaxError);
	if(expression.indexOf("UNDEFINED") != -1)
	{
		lbFormulaError.setText("Warning: There are parameters not yet defined in the formula.");
		lbFormulaError.setVisible(true);
		formulaWarning.setVisible(true);
	}
		
	lastComponents = {"tbxParameter": tbxNewParameter, "btnAdd": oBtnAdd, "tbFormula": lbFormula, "tbxFormula": tbxFormula};
	oDialog.addContent(tbxNewParameter);
	oDialog.addContent(oBtnAdd);
	oDialog.addContent(lbFormula);
	oDialog.addContent(tbxFormula);
	oDialog.addContent(formulaWarning);
	oDialog.addContent(lbFormulaError);
	oDialog.setWidth("320px");
	oDialog.setMaxWidth("320px");
	oDialog.setMinWidth("320px");

    oDialog.open();
}